// pages/admin/addproduct/addproduct.js
import { ProductModel }  from "../../../models/productModel.js"
import { CategoryModel } from "../../../models/CategoryModel.js"
import { MyDate } from "../../../models/MyDate.js"
import { ThemeModel } from "../../../models/ThemeModel.js"
let myDate = new MyDate()

let Product = new ProductModel()
let Category = new CategoryModel()
let Theme = new ThemeModel()
Page({
    _handlerSubmit:function(evt){
        console.log('evt',evt)
        let category = parseInt(evt.detail.value.productCategory)
 
        let price = parseFloat(evt.detail.value.productPrice)
        let theme = parseInt(evt.detail.value.productTheme)
        let name = evt.detail.value.productName
        let stock = parseInt(evt.detail.value.productStock)
        let sellPrice = parseFloat(evt.detail.value.productSellPrice)
        let productImages = this._spliceString(this.data.productImages,20,"product")
        let productDetails = this._spliceString(this.data.detailImages,20,"detail")
        let productTag = evt.detail.value.productTag

        if(true ){
        let  product = {
          product_name: name,
          product_price: price,
          product_imgs: productImages,
          detail_imgs :productDetails,
          product_stock: stock,
          product_theme: theme,
          product_sell_price: sellPrice,
          category_type: category,
          create_time: new Date(),
          update_time: new Date(),
          product_status: 0,
          sold_count:0,
          product_tag:productTag,
        }
        //上传图片
        this._uploadImages(this.data.productImages,"product")
        this._uploadImages(this.data.detailImages,"detail")
       
        console.log('product',product)
        Product.addProduct(product,res=>{
          console.log('添加成功',res)
        })
        wx.showToast({
          title: '商品添加成功',
          icon: 'success',
          duration: 1000,
          success:res=>{
            wx.navigateBack({
              delta: 1,
            })
          }
        })
        }
    },
    _spliceString:function(arrays,length,directory){
      let newarr = []
      console.log('array',arrays)
      arrays.forEach(element=>{
      let str = element.url.substr(element.url.length-length,element.url.length)
        newarr.push('/'+directory+'/'+str)
        console.log('for',str)
      })
      return newarr
    },
    _uploadFile:function(cloudPath,filePath){
      //检查文件是否存在
      if(filePath===""){
        //不存在
      }else{
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: cloudPath,
          // 指定要上传的文件的小程序临时文件路径
          filePath: filePath,
          // 成功回调
          success: res => {
            console.log('上传成功', res)
          },
        })
      }
    },
    /**
     * 页面的初始数据
     */
    data: {
      productName:'',
      nameError:'',
      stockError:'',
      priceError:'',
      sellPriceError:'',
      tagError:'',
      showButton:true,
      productThemes:[],
      productCategories: [ ],
      theme: 1,
      category: 1,
      productImages:[],//商品swipper
      detailImages:[],//商品详情
      imgList:[],
      product:{},
    },
    //文本输入校验
    onChange:function(event){
      let that = this
      let input = event.detail 
      let attribute = event.currentTarget.dataset.data
    
      //校验是否为空
      if(input == '' || input == null){
        that.setData({
          [attribute]:'输入不能为空'
        })
        that.checkInput()
      }else{
        that.setData({
          [attribute]:''
        })
        //校验格式是否错误
        switch(attribute){
            case 'stockError':
              {
                if(!that.checkNumber(input)){
                  that.setData({
                    [attribute]:'输入必须为正整数'
                  })
                }
              }break;
            case 'priceError':
            case 'sellPriceError':
                {
                  if(!that.checkPrice(input)){
                    that.setData({
                      [attribute]:'输入必须为数字'
                    })
                  }
                }break;
            default:{
                  that.setData({
                    [attribute]:''
                  })
                }
        }
        //校验输入合法性
        that.CheckMsg(input).then(res=>{
          if(!res){
            that.setData({
              [attribute]:'内容含有违法违规内容'
            })
          }
          that.checkInput()
        })
      }
   
    },
    inputTag:function(e){
      this.setData({
        'product.product_tag':e.detail
      })
    },

    //校验价格格式
    checkPrice:function(input){
     var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
     return reg.test(input)
    },
    checkNumber:function(input){
      var reg = /^[1-9]\d*$/;
      return reg.test(input)
    },
    checkInput:function(){
      if(this.data.nameError == '' && this.data.stockError == '' && this.data.priceError == '' && this.data.sellPriceError == '' && this.data.detailImages.length > 0 && this.data.productImages.length > 0){
        this.setData({
          showButton:false
        })
      }else{
        this.setData({
          showButton:true
        })
      }
    },
    onLoad: function (options) {
      this._init()
    },
    _init:function(){
      Category.getCateGory(res=>{
        let data1 = res.result.data.data
        var newArr = data1.map(function(item){
          return{
            text:item['category_name'],
            value:item['category_type']
          }
        })
        this.setData({
          productCategories: newArr
        })
      })
      Theme.getTheme(res=>{
        let data1 = res.result.data.data
        var newArr = data1.map(function(item){
          return{
            text:item['theme_name'],
            value:item['theme_type'],
            theme_icon:['theme_icon']
          }
        })
        this.setData({
          productThemes:newArr
        })
      })
    },
    delete:function(event){
      let productImages = this.data.productImages
      let index = event.detail.index
      productImages.splice(index,1)
      this.setData({productImages})
      this.checkInput()
    },
    deleteDetail:function(event){
      let detailImages = this.data.detailImages
      let index = event.detail.index
      detailImages.splice(index,1)
      this.setData({detailImages})
      this.checkInput()
    },
    _upload2:function(){
      this._upload(this.data.fileList,"test")
    },
    _uploadImages:function(images,directory){
      images.forEach(element=>{
        let imagepath = element.url
        let name = imagepath.substr(imagepath.length-20,imagepath.length)
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: directory+'/'+name,
          // 指定要上传的文件的小程序临时文件路径
          filePath: imagepath,
          // 成功回调
          success: res => {
            console.log('上传成功', res)
          },
        })
      })
    },
    //选择商品主图片
    afterRead(event) {
      let images = event.detail.file
      for(let i=0;i<images.length;i++){
      this.ImgCheck(images[i].path,i+1)
       // productImages.push({url:images[i].path})
      }
    },
    //选择商品详情图片
    afterReadDetail(event) {
      let images = event.detail.file
      console.log('event',event)
      for(let i=0;i<images.length;i++){
        this.detailImgCheck(images[i].path,i+1)
      }
    },
    
    CheckMsg:function(msg){ 
     let call =  wx.cloud.callFunction({
        name:'ContentCheck',
        data: {
          $url:'MsgCheck',
          msg:msg
        }
      }).then(MsgRes=>{
        if (MsgRes.result.data.errCode == "87014") {
          return Promise.resolve(false)
        }else{
          return Promise.resolve(true)
        }
      }).then(res=>{
         return res
      })
    return call
    },
  /**
   * 
   * @param {*} filePath  图片临时存储地址
   * @param {*} number    第几张图片
   * @param {*} max       可上传的图片最大数量
   */
   ImgCheck:function(filePath,number){
     wx.showLoading({
       title: '图片加载中',
     })
      // 图片转化buffer后，调用云函数
      let that = this
      wx.getFileSystemManager().readFile({
        filePath: filePath,  
        success: res => {
           wx.cloud.callFunction({
             name: "ContentCheck",
             data: {
               $url:'ImgCheck',
               ImgBuffer: res.data,
             }
           }).then(
             imgRes => { 
               if (imgRes.result.data.errCode == "87014") {
                 wx.hideLoading({
                   complete: (res) => {},
                 })
                 wx.showToast({
                   title: "图片"+number+"含有违法违规内容",
                   icon: "none"
                 })
               } else {
                 //图片正常 
                 wx.hideLoading({
                   complete: (res) => {},
                 })
                 if (that.data.productImages.length == 0) {
                   that.setData({
                     productImages: [{url:filePath}],
                   })
                   that.checkInput()
                 } else {   
                   that.setData({
                     productImages: that.data.productImages.concat({url:filePath})
                   })
                } 
               } 
             },
             function (error) {
               wx.hideLoading({
                 complete: (res) => {},
               })
               wx.showToast({
                 title: "失败，请重试",
                 icon: "none"
               })
          })
     },fail:res=>{
       console.log('readFile error',res)
     }
    }) 
   },
   detailImgCheck:function(filePath,number){
    wx.showLoading({
      title: '图片加载中',
    })
     // 图片转化buffer后，调用云函数
     let that = this
     wx.getFileSystemManager().readFile({
       filePath: filePath,  
       success: res => {
       wx.cloud.callFunction({
            name: "ContentCheck",
            data: {
              $url:'ImgCheck',
              ImgBuffer: res.data,
            }
          }).then(
            imgRes => { 
              if (imgRes.result.data.errCode == "87014") {
                wx.hideLoading({
                  complete: (res) => {},
                })
                wx.showToast({
                  title: "图片"+number+"含有违法违规内容",
                  icon: "none"
                })
              } else {
                //图片正常 
                wx.hideLoading({
                  complete: (res) => {},
                })
                if (that.data.detailImages.length == 0) {
                  that.setData({
                    detailImages: [{url:filePath}],
                  })
                  that.checkInput()
                } else {   
                  that.setData({
                    detailImages: that.data.detailImages.concat({url:filePath})
                  })
               } 
              } 
            },
            function (error) {
              wx.hideLoading({
                complete: (res) => {},
              })
              wx.showToast({
                title: "失败，请重试",
                icon: "none"
              })
              console.log("失败：" + error);
         })
    } 
   })
   
  },
  
})